package com.rest.demo;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

    private boolean isMultipart;
    private String filePath;
    private int maxFileSize = 950 * 1024 * 1024;
    private int maxMemSize = 4 * 1024 * 1024;
    private File file;

    public void init() {
        // Get the file location where it would be stored.
        filePath = "/home/mile/Public";
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            java.io.IOException {
        System.out.println("upload");
        // Check that we have a file upload request
        isMultipart = ServletFileUpload.isMultipartContent(request);

        String contentTypeG = request.getContentType();
        System.out.println("contentType " + contentTypeG);
        // response.setContentType("text/html");
        // java.io.PrintWriter out = response.getWriter();
        if (!isMultipart) {
            // out.println("<html>");
            // out.println("<head>");
            // out.println("<title>Servlet upload</title>");
            // out.println("</head>");
            // out.println("<body>");
            // out.println("<p>No file uploaded</p>");
            // out.println("</body>");
            // out.println("</html>");
            System.err.println("not multipart");
            response.sendError(405, "not a multipart");
            return;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(maxMemSize); // maximum size that will be
                                              // stored in memory

        factory.setRepository(new File("/home/mile/temp")); // Location to save
                                                            // data that is
                                                            // larger than
                                                            // maxMemSize.
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        System.out.println("all set");
        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            System.out.println("got fileitems");
            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    fi.write(file);
                    System.out.println("Uploaded Filename: " + fileName + "<br>");
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
            ex.printStackTrace();
            response.sendError(406, "error");
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            java.io.IOException {

        throw new ServletException("GET method used with " + getClass().getName() + ": POST method required.");
    }
}
